import mysql.connector
import os

# 数据库连接配置
DB_CONFIG = {
    'user': 'root',
    'password': 'diding2014',
    'host': 'localhost',
    'database': 'tarocake_team'
}

def get_table_names():
    # 创建数据库连接
    try:
        connection = mysql.connector.connect(**DB_CONFIG)
        cursor = connection.cursor()

        # 执行查询以获取所有表名
        cursor.execute("SHOW TABLES")
        table_names = [table[0] for table in cursor.fetchall()]

        return table_names

    except mysql.connector.Error as err:
        print(f"Error: {err}")
        return []

    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()

def save_table_names_to_file(table_names, file_name):
    # 保存表名到文件
    with open(file_name, 'w') as file:
        for name in table_names:
            file.write(f"{name}\n")
    print(f"Table names saved to {file_name}")

if __name__ == "__main__":
    table_names = get_table_names()
    if table_names:
        # 在当前目录创建输出文件名
        output_file = os.path.join(os.path.dirname(__file__), 'table_names.txt')
        save_table_names_to_file(table_names, output_file)
